package com.cyz.web.app.function.stream;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class Client {

    public static void main(String[] args) {

//        List<Author> authors = Author.getAuthors();

//        authors.stream().flatMap(author-> author.getBooks().stream()).collect(Collectors.toList());
//
//
//        authors.stream().flatMap(new Function<Author, Stream<Book>>() {
//            @Override
//            public Stream<Book> apply(Author author) {
//                return author.getBooks().stream();
//            }
//        }).flatMap(book-> Arrays.stream(book.getCategory().split(","))).distinct().forEach(category-> System.out.println(category));
//
//
            //使用flatmap将书的属性进行去重打印
//        authors.stream().flatMap((Function<Author, Stream<Book>>) author -> author.getBooks().stream())
//                .flatMap(book -> Arrays.stream(book.getCategory().split(","))).distinct()
//                .forEach(category -> System.out.println(category));
//
//
//
//        //获取作者的名字
//        var names = authors.stream().map(x -> x.getName()).collect(Collectors.toSet());
//        System.out.println(names);

        //将所有作者的书的价格求和
        test01();


    }

    private static void test01() {

       Stream<Author> authors = Author.getAuthors().stream();
        Stream<Author> authors2 = Author.getAuthors().stream();

        Optional<BigDecimal> allPrice = authors.flatMap((Function<Author, Stream<Book>>) author -> author.getBooks().stream())
                .map(book -> book.getPrice()).reduce((bigDecimal, bigDecimal2) -> bigDecimal.add(bigDecimal2));


        //简化
        Optional<BigDecimal> allPrice2 = authors2.flatMap((Function<Author, Stream<Book>>) author -> author.getBooks().stream())
                .map(book -> book.getPrice()).reduce(BigDecimal::add);


        log.info("所有书的价格是 {}, {}", allPrice.get(),  allPrice2.get());



    }

}
